﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using GWEB.WebBase.Entity;
using GWEB.WebBase.Utility;
using GWEB.WebFrame.Public;

namespace GWEB.WebFrame.Models
{
    public class FollowupList
    {
        public PageInfo Init()
        {
            PageInfo pg = new PageInfo();
            HttpSessionState session =System.Web.HttpContext.Current.Session;
            pg.dict = BasePage.getDict(session);
            pg.Type = "FollowupList";
            pg.LocateText = "查询";
            pg.SMenuId = "KH";
            pg.TableName = "cu_Customers";
            pg.KeyFieldName = "id";
            pg.Sop = BasePage.Grant(session, pg.SMenuId);
            pg.Sop.BROWSE = BasePage.Grant(session, pg.SMenuId, "GJ");
            pg.Sop.ADD = pg.Sop.EDIT = pg.Sop.DEL = false;
            pg.Tab.Add("已跟进", "LocatePara='';DataPageUrl='../Main/DataPageLay?type=FollowupList&state=0';GoPage(1);");
            pg.Tab.Add("今日预约", "LocatePara='';DataPageUrl='../Main/DataPageLay?type=FollowupList&state=1';GoPage(1);");
            pg.Tab.Add("明日预约", "LocatePara='';DataPageUrl='../Main/DataPageLay?type=FollowupList&state=2';GoPage(1);");
            pg.Tab.Add("本周预约", "LocatePara='';DataPageUrl='../Main/DataPageLay?type=FollowupList&state=3';GoPage(1);");
            pg.Tab.Add("今日生日宝宝", "LocatePara='';DataPageUrl='../Main/DataPageLay?type=FollowupList&state=4';GoPage(1);");
            pg.Tab.Add("试听学员", "LocatePara='';DataPageUrl='../Main/DataPageLay?type=FollowupList&state=5';GoPage(1);");
            pg.Tab.Add("订金学员", "LocatePara='';DataPageUrl='../Main/DataPageLay?type=FollowupList&state=6';GoPage(1);");
            pg.Tab.Add("合同学员", "LocatePara='';DataPageUrl='../Main/DataPageLay?type=FollowupList&state=7';GoPage(1);");
            pg.Tab.Add("30内合同到期", "LocatePara='';DataPageUrl='../Main/DataPageLay?type=FollowupList&state=8';GoPage(1);");

            HttpRequest request = System.Web.HttpContext.Current.Request;
            String state = Fun.cString(request["state"]);
            String condition = "";

            //按钮
            String button = "";
            switch (state)
            {
                case "0":
                    //
                    condition = String.Format(" and custState>=3 ");
                    button += "<a href=\"javascript:ShowModalUrl('popEdit', '../Customer/Followup?id=-1&Ids=[id]&KeyCodes='+ GetKeyCode('[id]'), '跟进', '', '', '') \"  class='layui-btn layui-btn-xs'>跟进</a>";
                    break;
                case "1"://今日预约
                case "2"://明日预约
                case "3"://本周预约
                case "4"://今日生日宝宝
                    String remark = "";
                    if (state == "1")
                    {
                        remark = "今日预约提醒";
                        condition = String.Format(" and custState=4  and convert(varchar(10),getdate(),120)=convert(varchar(10),NextMakeDate,120) ");
                    }
                    else if (state == "2")
                    {
                        remark = "明日预约提醒";
                        condition = String.Format(" and custState=4  and  convert(varchar(10),getdate(),120)=convert(varchar(10),NextMakeDate-1,120)  ");
                    }
                    else if (state == "3")
                    {
                        remark = "本周预约提醒";
                        condition = String.Format(" and custState=4  and year(getdate())=year(NextMakeDate) and datepart(ww,getdate()-1)=datepart(ww,NextMakeDate-1)  ");
                    }
                    else if (state == "4")
                    {
                        remark = "宝宝生日提醒";
                        condition = String.Format(" and custState>=3  and month(getdate())=month(BirdDate) and day(getdate())=day(BirdDate) ");
                    }

                    button += "<a href=\"javascript: layer.confirm('您确定要提醒吗？', function (index) {layer.close(index);Do('../Customer/FollowupList/Remind',{ id:[id],keyCode: GetKeyCode('[id]'),remark:'"+ remark + "'});})\"  class='layui-btn layui-btn-xs layui-btn-danger'>提醒</a>";
                    button += "<a href=\"javascript:ShowModalUrl('popEdit', '../Customer/Followup?id=-1&Ids=[id]&KeyCodes='+ GetKeyCode('[id]'), '跟进', '', '', '') \"  class='layui-btn layui-btn-xs'>跟进</a>";
                    break;                
                case "5"://试听学员
                    condition = String.Format(" and t6.cid is not null ");
                    button += "<a href=\"javascript:parent.AddWin('../Main/ManagerLay?type=FollowupAudition&Ids=[id]&KeyCodes='+ GetKeyCode('[id]')+'&isCheck=0','试听详情-[custName]') \"  class='layui-btn layui-btn-xs layui-btn-normal'>试听详情</a>";
                    button += "<a href=\"javascript: layer.confirm('您确定要提醒吗？', function (index) {layer.close(index);Do('../Customer/FollowupList/Remind',{ id:[id],keyCode: GetKeyCode('[id]'),remark:'试听提醒'});})\"  class='layui-btn layui-btn-xs layui-btn-danger'>提醒</a>";                    
                    button += "<a href=\"javascript:ShowModalUrl('popEdit', '../Customer/Followup?id=-1&Ids=[id]&KeyCodes='+ GetKeyCode('[id]'), '跟进', '', '', '') \"  class='layui-btn layui-btn-xs'>跟进</a>";                    

                    //button += "<a href=\"javascript:ShowModalUrl('popEdit', '../Customer/Followup?id=-1&Ids=[id]&KeyCodes='+ GetKeyCode('[id]'), '退费', '', '', '') \"  class='layui-btn layui-btn-xs'>退费</a>";
                    //button += "<a href=\"javascript:ShowModalUrl('popEdit', '../Customer/Followup?id=-1&Ids=[id]&KeyCodes='+ GetKeyCode('[id]'), '收费', '', '', '') \"  class='layui-btn layui-btn-xs'>收费</a>";
                    break;
                case "6"://订金学员
                    condition = String.Format(" and custState=5 ");                    
                    button += "<a href=\"javascript:parent.AddWin('../Main/ManagerLay?type=FollowupDeposit&Ids=[id]&KeyCodes='+ GetKeyCode('[id]')+'&isCheck=0','订金详情-[custName]') \"  class='layui-btn layui-btn-xs layui-btn-normal'>订金详情</a>";
                    //button += "<a href=\"javascript:ShowModalUrl('popEdit', '../Customer/Followup?id=-1&Ids=[id]&KeyCodes='+ GetKeyCode('[id]'), '退订金', '', '', '') \"  class='layui-btn layui-btn-xs'>退订金</a>";
                    //button += "<a href=\"javascript:ShowModalUrl('popEdit', '../Customer/Followup?id=-1&Ids=[id]&KeyCodes='+ GetKeyCode('[id]'), '修改签约时间', '', '', '') \"  class='layui-btn layui-btn-xs'>修改签约时间</a>";
                    break;
                case "7"://合同学员
                    condition = String.Format(" and custState=6 ");
                    button += "<a href=\"javascript:parent.AddWin('../Main/ManagerLay?type=FollowupContract&Ids=[id]&KeyCodes='+ GetKeyCode('[id]')+'&isCheck=0','合同详情-[custName]') \"  class='layui-btn layui-btn-xs layui-btn-normal'>合同详情</a>";
                    //button += "<a href=\"javascript:ShowModalUrl('popEdit', '../Customer/Followup?id=-1&Ids=[id]&KeyCodes='+ GetKeyCode('[id]'), '合同详情', '', '', '') \"  class='layui-btn layui-btn-xs'>合同详情</a>";
                    //button += "<a href=\"javascript:ShowModalUrl('popEdit', '../Customer/Followup?id=-1&Ids=[id]&KeyCodes='+ GetKeyCode('[id]'), '退合同', '', '', '') \"  class='layui-btn layui-btn-xs'>退合同</a>";
                    //button += "<a href=\"javascript:ShowModalUrl('popEdit', '../Customer/Followup?id=-1&Ids=[id]&KeyCodes='+ GetKeyCode('[id]'), '延期', '', '', '') \"  class='layui-btn layui-btn-xs'>延期</a>";
                    break;
                case "8"://30内合同到期
                    condition = String.Format(" and custState=6 and datediff(dd,t7.ConEnd,getdate()) between 0 and 30 ");//已过期不会显示
                    break;
                default:
                    break;
            }
            button += "<a href =\"javascript:ShowModalUrl('popEdit', '../Customer/CustomerMore?id=[id]&keyCode='+GetKeyCode([id]), '详情', '', '', '')\" class='layui-btn layui-btn-primary layui-btn-xs'>详情</a><a href=\"javascript:ShowModalUrl('popEdit', '../Customer/CustomerEdit?id=[id]&keyCode='+GetKeyCode([id]), '补充', '', 700, 500)\" class='layui-btn layui-btn-primary layui-btn-xs'>补充</a>";

            pg.Sql = String.Format(@"
select * from (
    select t1.*,
        datediff(m,BirdDate,getdate()) custMonth,		
        t2.dname custStateCn,
		datediff(hh,getdate(),t4.createDate)+ReceInterval as receHour,
		t5.FollowupCount,
        t7.Constart,
        t6.makeDate,t8.CourseName,
        ltrim(t9.sumAccount0)+'/'+ltrim(t9.sumAccount1) sumAccount01,
        ltrim(t9.sumAccount2)+'/'+ltrim(t9.sumAccount3) sumAccount23,
        t9.sumAccount4,t9.sumAccount5,
        t10.conCount,
        ltrim(t10.DisPrice)+'/'+ltrim(t10.ContractPrice) ContractPrice,
        ltrim(t10.SurplusNumber)+'/'+ltrim(t10.TotalCourseNumber) TotalCourseNumber,
        t10.DepositPrice,
        t10.SurplusContractPrice,case when latelyConEnd='9999-12-30' then null else  latelyConEnd end as latelyConEnd,
		'' link
    from cu_Customers t1
    left join tb_sys_dictionary t2 on t1.CustState = t2.did and t2.typeid = 'D01'
    left join (
	    select cid,min(createDate) contractDate from cu_Contract group by cid
    ) t3 on t1.id=t3.cid
	inner join (
		select ROW_NUMBER() over(partition by cid order by id desc) rn,cid,createDate,ReceInterval from cu_Cus_Distribution
	) t4 on t4.rn=1 and t4.cid=t1.id
	inner join (
		select cid,count(*) FollowupCount,sum(case when isAuditions=1 then 1 else 0 end) auditionCount from cu_Cus_followup group by cid
	) t5 on t5.cid=t1.id
    left join (
        select ROW_NUMBER() over(partition by cid order by id desc) rn,cid,makeDate,CourseId,CourseState from cu_Cus_followup where IsAuditions=1
    ) t6 on t6.rn=1 and t6.cid=t1.id
    left join cu_Contract t7 on t1.contractId=t7.id   
    left join cu_Course t8 on t6.CourseId=t8.id
    left join (
        select cid,
	        sum(case when state=3 then Account else 0 end) sumAccount0,--已使用
	        sum(case when state<=3 then Account else 0 end) sumAccount1,--总额
	        sum(case when state=0 then Account else 0 end) sumAccount2,--未入帐
	        sum(case when state<3 then Account else 0 end) sumAccount3,--未使用
	        sum(case when state=4 then Account else 0 end) sumAccount4,--已作废
	        count(*) sumAccount5--订金条数
        from cu_Account where FlowingType in ('00101001','00201001')
        group by cid
    ) t9 on t1.id=t9.cid
left join (
   select cid,count(*) conCount,
	    sum(DisPrice) DisPrice,sum(ContractPrice) ContractPrice,
	    sum(SurplusNumber) SurplusNumber,sum(ConCourseNumber)+sum(GiveCourseNumber) as TotalCourseNumber,
		sum(DepositPrice) DepositPrice,
	    SUM(case when status in (2,3,4) then
			case 
				when t3.IsClassHour=1 then (SurplusNumber-GiveCourseNumber)*DisPrice/ConCourseNumber --按次算
				when DATEDIFF(dd,getdate(),courseEnd)+1>=0 then --按天数
						(DATEDIFF(dd,getdate(),courseEnd)+1)*DisPrice/DATEDIFF(dd,courseStart,courseEnd)
                else 0
			end
		else 0 end) SurplusContractPrice,
	    min(case when getdate()<=conEnd then conEnd else '9999-12-30' end) latelyConEnd
    from cu_Contract t1
	left join (
        select ContractId,sum(account) DepositPrice  
        from cu_Account where state=3 and  flowingtype in('00101001','00201001') group by ContractId
    ) t2 on t1.id=t2.ContractId
	left join cu_Contract_class t3 on t1.SetmealId=t3.id
    group by cid
) t10 on t1.id=t10.cid
    where 1=1 {0}
) cu_Customers where 1=1", condition);
            ColumnInfo cl;
            cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "custName"; cl.HeadText = "宝宝姓名"; cl.IsCondition = true; cl.ConditionPosition = 1; pg.AddColumn(cl);
            cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "childName"; cl.HeadText = "宝宝小名"; cl.IsCondition = true; pg.AddColumn(cl);
            cl = new ColumnInfo(); cl.DataType = Tag.Decimal; cl.FieldName = "custMonth"; cl.HeadText = "月龄"; cl.IsCondition = true; pg.AddColumn(cl);
            cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "linkName"; cl.HeadText = "家长姓名"; cl.IsCondition = true; cl.ConditionPosition = 1; pg.AddColumn(cl);
            cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "custTel"; cl.HeadText = "联系电话"; cl.IsCondition = true; cl.ConditionPosition = 1; pg.AddColumn(cl);
            cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "custFromId"; cl.HeadText = "渠道来源"; cl.IsCondition = true; cl.Visible = false; cl.DictTypeID = "D03"; pg.AddColumn(cl);
            cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "custFrom"; cl.HeadText = "渠道来源"; pg.AddColumn(cl);

            cl = new ColumnInfo(); cl.DataType = Tag.Decimal; cl.FieldName = "FollowupCount"; cl.HeadText = "跟进次数"; cl.IsCondition = true; pg.AddColumn(cl);
            cl = new ColumnInfo(); cl.DataType = Tag.DateTime; cl.FieldName = "LateLyDistDate"; cl.HeadText = "最近分配时间"; cl.IsCondition = true; pg.AddColumn(cl);
            cl = new ColumnInfo(); cl.DataType = Tag.DateTime; cl.FieldName = "latelyFoupDate"; cl.HeadText = "最近跟进时间"; cl.IsCondition = true; pg.AddColumn(cl);
            switch (state)
            {
                case "0":
                    cl = new ColumnInfo(); cl.DataType = Tag.Date; cl.FieldName = "NextMakeDate"; cl.HeadText = "下次联系时间"; cl.IsCondition = true; cl.Style = "color:#FFB800"; pg.AddColumn(cl);
                    break;
                case "1"://今日预约                   
                case "2"://明日预约
                case "3"://本周预约
                    cl = new ColumnInfo(); cl.DataType = Tag.Date; cl.FieldName = "NextMakeDate"; cl.HeadText = "预约时间"; cl.IsCondition = true; cl.Style = "color:#FFB800"; pg.AddColumn(cl);
                    break;
                case "4"://今日生日宝宝
                    cl = new ColumnInfo(); cl.DataType = Tag.Date; cl.FieldName = "BirdDate"; cl.HeadText = "出生日期"; cl.IsCondition = true; cl.Style = "color:#FFB800"; pg.AddColumn(cl);
                    break;
                case "5"://试听
                    cl = new ColumnInfo(); cl.DataType = Tag.Decimal; cl.FieldName = "auditionCount"; cl.HeadText = "试听数量"; cl.IsCondition = true;pg.AddColumn(cl);
                    cl = new ColumnInfo(); cl.DataType = Tag.Date; cl.FieldName = "makeDate"; cl.HeadText = "试听时间"; cl.IsCondition = true; cl.Style = "color:#FFB800"; pg.AddColumn(cl);
                    cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "CourseName"; cl.HeadText = "试听课程"; cl.IsCondition = true; cl.Style = "color:#FFB800"; pg.AddColumn(cl);
                    break;
                case "6"://订金  --0未入帐，2已入帐，3已使用，4已作废        
                    cl = new ColumnInfo(); cl.DataType = Tag.Date; cl.FieldName = "Constart"; cl.HeadText = "最近签约时间"; cl.IsCondition = true; cl.Style = "color:#FFB800"; pg.AddColumn(cl);
                    cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "sumAccount01"; cl.HeadText = "已使用/总额"; cl.Style = "color:#FFB800"; pg.AddColumn(cl);
                    cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "sumAccount23"; cl.HeadText = "未入账/未使用"; cl.Style = "color:#FFB800"; pg.AddColumn(cl);
                    cl = new ColumnInfo(); cl.DataType = Tag.Decimal; cl.FieldName = "sumAccount4"; cl.HeadText = "作废金额"; cl.Style = "color:#FFB800"; pg.AddColumn(cl);
                    cl = new ColumnInfo(); cl.DataType = Tag.Decimal; cl.FieldName = "sumAccount5"; cl.HeadText = "订金条数"; cl.Style = "color:#FFB800"; pg.AddColumn(cl);
                    break;
                case "7":
                case "8":
                    cl = new ColumnInfo(); cl.DataType = Tag.Decimal; cl.FieldName = "conCount"; cl.HeadText = "合同条数"; cl.Style = "color:#FFB800"; pg.AddColumn(cl);
                    cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "ContractPrice"; cl.HeadText = "实收金额/合同金额"; cl.Style = "color:#FFB800"; pg.AddColumn(cl);
                    cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "TotalCourseNumber"; cl.HeadText = "剩余课时/总课时"; cl.Style = "color:#FFB800"; pg.AddColumn(cl);
                    cl = new ColumnInfo(); cl.DataType = Tag.Decimal; cl.FieldName = "DepositPrice"; cl.HeadText = "使用订金总额"; cl.Style = "color:#FFB800"; pg.AddColumn(cl);
                    cl = new ColumnInfo(); cl.DataType = Tag.Decimal; cl.FieldName = "SurplusContractPrice"; cl.HeadText = "剩余合同金额"; cl.Style = "color:#FFB800"; pg.AddColumn(cl);
                    cl = new ColumnInfo(); cl.DataType = Tag.Date; cl.FieldName = "latelyConEnd"; cl.HeadText = "最近合同到期"; cl.IsCondition = true; cl.Style = "color:#FFB800"; pg.AddColumn(cl);

                    break;
            }
            //已跟进=跟进次数，最近分配时间 跟进时间 下次联系时间
            //到访=跟进次数，最近分配时间 跟进时间 预约时间（标色）
            //生日=跟进次数，最近分配时间 跟进时间 出生日期（标色）
            //试听=跟进次数，最近分配时间 跟进时间 试听数量 试听时间 试听课程 --入账状态
            //订金=跟进次数，最近分配时间 跟进时间  最近签约时间 已使用/总额	未入账/未使用	作废金额	订金条数
            //合同：合同条数	实收金额/合同金额	使用订金总额	剩余课时/总课时	剩余合同金额	最近合同到期

            cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "custState"; cl.HeadText = "状态"; cl.IsCondition = true; cl.Visible = false; cl.DictTypeID = "D01"; pg.AddColumn(cl);
            cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "custStateCn"; cl.HeadText = "状态"; pg.AddColumn(cl);
            if (!button.Equals(""))
            { cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "link"; cl.HeadText = "操作"; cl.IsSort = false; cl.Script = button; pg.AddColumn(cl); }

            return pg;
        }
    }
}